import React from 'react';
import { observer } from 'mobx-react';
import { WeaSearchGroup, WeaFormItem,WeaLocaleProvider,WeaTools} from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import _ from 'lodash';
import $ from 'jquery';
import {spellResourceCondition,} from '../../util';
const getLabel = WeaLocaleProvider.getLabel;

interface AdvancedSearchsProps{
    form:any, 
    conditioninfo:any, 
    customComponent?: any, 
    quickSearch?: Function,
    listStore?:any
}

@observer
export default class AdvancedSearchs extends React.Component<AdvancedSearchsProps,any>{
    formParams = {};

    changeQuickSearchData1 =(form,conditioninfo,domkey) => {
        const clearField = (key) => {
            conditioninfo.map((c)=>{
                c.items.map(item => {
                    if(item.parentDomkey && item.parentDomkey[0] == key){
                        form.$(item.domkey[0]).value = '';
                        clearField(item.domkey[0])
                    }
                })
            })
        }
        clearField(domkey)
    }

    getFields = (field: any, conditioninfo, form) => {
        if (field.parentDomkey && field.parentDomkey.length > 0) {
            let items: any = {};
            conditioninfo.map((c) => {
                c.items.map(f => {
                    if (f.domkey == field.parentDomkey[0]) {
                        const value1 = form.$(f.domkey).values() ? form.$(f.domkey).values() : WeaTools.getSelectDefaultValue(f.options);
                        let childitem:any = []
                        value1.split(',').map((val)=>{
                            childitem = _.union(childitem,f.options.filter(o => o.key == val))
                        })
                        let childitemid:any = [];
                        childitem.map((item)=>{
                            childitemid = _.union(childitemid,item.childitemid)
                        })
                        let childArry: any = [];
                        for (let i = 0; i < childitemid.length; i++) {
                            const arr = field.options.filter(option => option.key == childitemid[i] || option.key == "");
                            childArry = _.union(childArry, arr);
                        }
                        // field.options = childArry;
                        field = {...field,options:childArry}
                        items = field;
                    } else {
                        items = field;
                    }
                })
            })
            return items
        } else {
            return field;
        }
    }

    getParams = (field: any, key) => {
        if (key in field) {
            return field[key];
        } else {
            if (field.otherParams) {
                return field.otherParams[key];
            }
        }
    }
    /** 重新计算蒙层的高度 */
     recalculateMask = () => {
        let domRootStr =  '';
        if($(".coms-mode-top-title-advanced").length>0){
            domRootStr = "coms-mode-top-title-advanced";
        }else if($(".cube_board").length>0){
            domRootStr = "cube_board";
        }
        if(domRootStr){
            let dom = $(`.${domRootStr} .wea-search-container`)[0];
            if(dom){
                let maskDarkHeight = window.innerHeight - dom.offsetTop - 110;
                $(`.${domRootStr} .mask-dark`).height(maskDarkHeight);
            }
        }
    }

    func = () => {
        const {quickSearch} = this.props;
        quickSearch && setTimeout(quickSearch, 50)
    }

    render(){
        const {form, conditioninfo, customComponent=''} = this.props;
        const { isFormInit } = form;
        let group = [] as any[];
        if (isFormInit) {
            const formParamsTemp = form.getFormParams();
            for(let param in formParamsTemp){
                this.formParams[param] = formParamsTemp[param];
            }
            // isFormInit 为true，form已经初始化完成
            isFormInit && conditioninfo.map((c) => {
                let items = [] as any[];
                let Timedata = [
                    { showname: getLabel(332, '全部'), key: '0', selected: true },
                    { showname: getLabel(517615, '昨天'), key: '9' , selected: false },
                    { showname: getLabel(15537, '今天'), key: '1', selected: false },
                    { showname: getLabel(517616, '明天'), key: '10' , selected: false },
                    { showname: getLabel(517617, '上周'), key: '11', selected: false  },
                    { showname: getLabel(15539, '本周'), key: '2', selected: false  },
                    { showname: getLabel(517618, '下周'), key: '12' , selected: false },
                    { showname: getLabel(15541, '本月'), key: '3' , selected: false },
                    { showname: getLabel(21904, '本季'), key: '4' , selected: false },
                    { showname: getLabel(15384, '本年'), key: '5', selected: false  },
                    { showname: getLabel(27347, '上个月'), key: '7', selected: false  },
                    { showname: getLabel(81716, '上一年'), key: '8' , selected: false },
                    { showname: getLabel(32530, '指定日期范围'), key: '6' }  // 时间范围的值必须为6
                ]
    
                c.items.map(fields => {
                    // fields['style']={width:'95%'};
                    const func2 = (fieldObj,datas) => {
                        if(fields.conditionType === 'BROWSER' && fields.browserConditionParam.type == '141'){
                            // 更新表单
                            let ids = spellResourceCondition(datas.valueObj);
                            fieldObj[fields.domkey[0]].value = ids;
                            form.updateFields(fieldObj);
                        }else if(fields.conditionType === 'SELECT'){
                            this.changeQuickSearchData1(form,conditioninfo,fields.domkey[0])
                        }
                    }
                    if (fields.conditionType === 'BROWSER') {
                        const {type} = fields.browserConditionParam;
                        if(type&&(type=="161"||type=="162"||type=="256"||type=="257")){
                            fields={
                                ...fields,
                                browserConditionParam:{
                                    ...fields.browserConditionParam,
                                    completeParams:{ ...fields.browserConditionParam.completeParams,  ...this.formParams,  consearch:"consearch" },
                                    conditionDataParams:{ ...fields.browserConditionParam.conditionDataParams, ...this.formParams,consearch:"consearch" },
                                    dataParams:{ ...fields.browserConditionParam.dataParams, ...this.formParams,consearch:"consearch" }
                                }
                            }
                        }
                        if (type&&(type == '4' ||type == '57'||type == '164'  ||type == '169'||type == '194'|| type == '167'|| type == '170'|| type == '168')){   //部门，多部门，分部，多分部，单点分权，分权单部门，分权多分部，分权多部门
                            fields.browserConditionParam.dataParams['fromModule'] = "model";
                            fields.browserConditionParam.destDataParams['fromModule'] = "model";
                            fields.browserConditionParam.completeParams['fromModule'] = "model";
                        }
                    }
                    //多分部处理
                    if (fields.conditionType === 'SELECT_LINKAGE' && fields.selectLinkageDatas) {
                        for(var i in fields.selectLinkageDatas){
                            fields.selectLinkageDatas[i].browserConditionParam.dataParams['fromModule'] = "model";
                        }
                    }
                    if(fields.otherParams && fields.otherParams.tips ){
                        fields.helpfulTip = fields.otherParams.tips;
                        fields.helpfulTipProps.width = fields.tipsWidth || 320;
                    }
                    if(fields.conditionType=='DATE'){
                        items.push({
                            com: (<WeaFormItem
                                label={`${fields.label}`}
                                labelCol={{ span: fields.labelcol }}
                                wrapperCol={{ span: fields.fieldcol }}>
                                <WeaSwitch fieldConfig={{...this.getFields(fields, conditioninfo, form),options:[...Timedata]} } form={form} formParams={this.formParams} onChange={this.getParams(fields, "quickSearch") ? this.func : func2}/>
                            </WeaFormItem>),
                            colSpan: 1
                        })
    
                    }else{
                        items.push({
                            com: (<WeaFormItem
                                label={`${fields.label}`}
                                labelCol={{ span: fields.labelcol }}
                                wrapperCol={{ span: fields.fieldcol }}>
                                <WeaSwitch fieldConfig={this.getFields(fields, conditioninfo, form)}  form={form} formParams={this.formParams} onChange={this.getParams(fields, "quickSearch") ? this.func : func2}/>
                            </WeaFormItem>),
                            colSpan: 1
                        })
                    }
    
    
                });
                group.push(<WeaSearchGroup
                    needTigger={true}
                    title={c.title}
                    showGroup={c.defaultshow}
                    items={items}
                    customComponent={customComponent}
                    onVisibleChange={this.onVisibleChange}
                    className='cube-search-advance'
                />)
            });
        }
        return group;
    }

    onVisibleChange = (isVisible)=>{
        const {listStore} = this.props;
        if(listStore && listStore.isShowCondition && !isVisible) { //#879462 启用查询条件展开，点击收缩，将整个高级搜索收起来
            listStore.condition.visible = isVisible;
        }
        this.recalculateMask();
    }

}